//权限相关操作
import axios from 'axios';
//import {Message} from 'element-ui'


/* 初始化菜单操作 */
export const initMenu = (router,store)=> {
    //如果vuex的状态管理中存在路由信息，则不需要再次请求
    if (store.state.children.length > 0) {
        window.console.log("状态管理器中存在路由信息.....")
        return;
    }
    if(!window.localStorage.getItem("user") || !store.state.user.empName){
        return;
    }
    let empName = JSON.parse(localStorage.getItem('user')).empName;
    axios.get("http://localhost:8088/come/myemprouter?empName="+empName).then(resp=> {
        if (resp && resp.status == 200) {
            let res = resp.data;
            if(res.length>0 &&(store.state.children.length==undefined||store.state.children.length==0)){
                //1、对后台查询到的菜单信息，就行格式化，主要目的是：要符合Vue的路由的要求
                var fmtRoutes = formatRoutes(res);
                //2、将菜单信息，添加到路由对象中
                //store.state.children.push(fmtRoutes);
                router.addRoutes(fmtRoutes);

                //3、调用./src/store/in
                // dex.js中的方法initMenu，参数是格式化之后的菜单数组
                store.commit('initMenu',fmtRoutes);
                window.console.log("路由提交成功");
            }else{
                //Message.warning({message:"失败"});
                //router.replace({path: '/'});
            }

        }
    })

}

export const formatRoutes = (routes)=> {
    let fmRoutes = [];
    routes.forEach(router=> {
        let {
            path,
            name,
            component,
            meta,
            children
        } = router;
        if (children && children instanceof Array) {
            children = formatRoutes(children);
        }
        let fmRouter = {
            path: path,
            name: name,
            component(resolve){
                require(['../components/' + component], resolve)
            },
            meta: meta,
            children: children
        };
        fmRoutes.push(fmRouter);
    });
    return fmRoutes;
}
